package server.server;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import server.operation.Operation;
import server.operation.impl.LoginOperation;

/**
 * 客户端处理线程
 * @author skywalker
 *
 */
public class Worker implements Runnable {
	
	private static final Logger logger = LogManager.getLogger("server.Worker");
	private static final String INPUT_CHARSET = "UTF-8";
	private static final Operation[] operationMapper = {
		//零号没有任何操作
		null,
		new LoginOperation()
	};
	
	private final Socket socket;
	
	public Worker(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		BufferedReader br = null;
		BufferedOutputStream bos = null;
		try {
			br = new BufferedReader(new InputStreamReader(socket.getInputStream(), INPUT_CHARSET));
			String json = br.readLine();
			if (StringUtils.isNotEmpty(json)) {
				//解析客户端传来的json串
				JSONObject node = JSONObject.fromObject(json);
				int key = node.getInt("operation");
				if (key > 0) {
					String result = operationMapper[key].operate(node);
					//向客户端返回处理结果
					bos = new BufferedOutputStream(socket.getOutputStream());
					bos.write(result.getBytes());
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error(INPUT_CHARSET + "编码不被支持");
		} catch (IOException e) {
			//客户端已断开连接
			logger.error(socket.getInetAddress().toString() + "断开连接");
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (bos != null) {
					bos.close();
				}
				socket.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		
	}

}
